<?php
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\system\model\systemUser as systemUserModel;
use app\user\model\User as UserModel;
use app\product\model\Product as ProductModel;
use app\shouyin\model\Deposit as DepositModel;
use app\warehouse\model\Stock as StockModel;
use think\Db;
class Deposit extends Admin
{
    protected $hisiModel = 'Deposit';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名
    protected function initialize()
    {
        parent::initialize();
        $admin = systemUserModel::get(ADMIN_ID);

        $this->assign('admin_type',$admin['type']);
        $users = UserModel::getSelect(UserModel::all());
        $this->assign('users', $users);
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $where = [];

            $where['shop_id'] = session('shop_id');

            // 会员
            // 负责人
            $admins = systemUserModel::where($where)->all();
            $this->assign('admins', systemUserModel::getSelect($admins));

            // 产品
            $products = ProductModel::all();
            $this->assign('products', ProductModel::getSelect($products));

        }
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $user_id    = $this->request->param('user_id', '');
            $start    = $this->request->param('start', '2000-01-01');
            $end    = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
            }
            // halt($end);
            if(!is_empty($this->request->param('type')) && $this->request->param('type') == 2){
                $data['data'] = DepositModel::where($where)
                                ->whereTime('createtime', [strtotime($start), strtotime($end)])
                                ->field('*,user_id as user_name, product_id as product_name, admin_id as admin_name')
                                ->order('id desc')
                                ->select();

                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['warehouse'] = Db::name('warehouse')->where('id',$value['warehouse_id'])->value('name');
                    $data['data'][$key]['take_num'] = Db::name('deposit_log')->where('d_id',$value['id'])->sum('product_num_l');

                    if($value['status'] == 1){
                        $status = '寄存';
                    }else if($value['status'] == 2){
                        $status = '领取';
                    }else if($value['status'] == 3){
                        $status = '部分领取';
                    }
                    $data['data'][$key]['status']  = $status;
                }
                $data['count'] = DepositModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
                $data['code'] = 0;
                return json($data);
            }else{
                $data['data'] = DepositModel::where($where)
                                ->whereTime('createtime', [strtotime($start), strtotime($end)])
                                ->field('*,user_id as user_name, product_id as product_name, admin_id as admin_name')
                                ->page($page)
                                ->limit($limit)
                                ->order('id desc')
                                ->select();

                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['warehouse'] = Db::name('warehouse')->where('id',$value['warehouse_id'])->value('name');
                }
                $data['count'] = DepositModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
                $data['code'] = 0;
                return json($data);
            }

        }
        return $this->fetch();
    }

    public function take()
    {
        $id = $this->request->param('id');
        $formData = Db::name('deposit')->where('id', $id)->find();


        $formData['specs'] = Db::name('product')->where('id',$formData['product_id'])->value('specs');

        $formData['num_l'] = Db::name('deposit_log')->where('d_id',$formData['id'])->sum('product_num_l');

        $formData['num_s'] = $formData['num'] - $formData['num_l'];
        // hal
        if($this->request->isPost()){
            $postData        = $this->request->post();
            if(strpos($postData['product_num_l'],'.')){
                $postData['product_num_l'] = (float)$postData['product_num_l'];
            }
            
            if (empty($postData['id'])) {
                return $this->axiosMsg('缺少id参数',false);
            }
            if($postData['product_num_l'] == 0){
                return $this->axiosMsg('领取数量不能为0',false);
            }
            if($postData['product_num_l'] > $formData['num_s']){
                return $this->axiosMsg('领取数量超过剩余数量',false);
            }
            if(!isset($postData['ware_id']) || empty($postData['ware_id'])){
                return $this->axiosMsg('出库仓库为必填项',false);
            }
            if($formData['num_s'] - $postData['product_num_l'] == 0){
                $status = 2;
            }else{
                $status = 3;
            }
            // $warehouse_id = Db::name('warehouse')->where('shop_id',$formData['shop_id'])->where('type',1)->value('id');
            Db::startTrans();
            try {
                $price = $formData['price'];//总价格
                $unit_price = $formData['unit_price'];
                if(is_float($postData['product_num_l'])){
                    $stock_num = $postData['product_num_l'] * $formData['specs'];
                }else{
                    $stock_num = $postData['product_num_l'];
                }
                // halt($stock_num);
                $StockModel = new StockModel;
                $begin_num = $StockModel->getBeginNum($postData['ware_id'],$postData['product_id']);
                // $warehouse_id = 
                $stockDuctArr = [];
                $stockDuctArr['sn'] = $formData['sn'];
                $stockDuctArr['product_id'] = $postData['product_id'];
                $stockDuctArr['product_num'] = $stock_num;
                $stockDuctArr['product_name'] = $postData['product_name'];
                $stockDuctArr['shop_id'] = $formData['shop_id'];
                $stockDuctArr['type'] = '出库';
                $stockDuctArr['bak'] = '寄存单产品出库';
                $stockDuctArr['detailed_type'] = 2;
                $stockDuctArr['user_id'] = $formData['user_id'];
                $stockDuctArr['warehouse_id'] = $postData['ware_id'];
                $stockDuctArr['createtime'] = time();
                $stockDuctArr['status'] = 1;
                $stockDuctArr['price'] = $price / $formData['num'] * $postData['product_num_l'];
                $stockDuctArr['unit_price'] = $unit_price / $formData['num'] * $postData['product_num_l'];
                $stockDuctArr['begin_num']     = $begin_num;
                $stockDuctArr['end_num']       = $begin_num - $stock_num;

                Db::name('stock')->insert($stockDuctArr);

                $postData['d_id']  = $postData['id'];
                unset($postData['id']);
                unset($postData['specs']);
                $postData['createtime'] =  date('Y-m-d H:i:s',time());
                $postData['unit_price'] = $unit_price / $formData['num'] * $postData['product_num_l'];
                Db::name('deposit_log')->insert($postData);

                Db::name('deposit')->where('id',$id)->update(['status'=>$status]);

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return $this->axiosMsg($e->getMessage(),false);
            }

            return $this->axiosMsg('领取成功！', true);
        }
        if(!$formData){
            return $this->error('订单不存在或权限不足');
        }
        $formData['user_name'] = Db::name('user')->where('id', $formData['user_id'])->value('nick');
        $formData['product_name'] = Db::name('product')->where('id', $formData['product_id'])->value('name');
        $this->assign('formData', $formData);

        $warehouses = Db::name('warehouse')->field('id,name')->where('shop_id',session('shop_id'))->select();
        $this->assign('warehouses',$warehouses);
        return $this->fetch();
    }

    public function look()
    {
        $id = $this->request->param('id');
        $list = Db::name('deposit_log')->where('d_id',$id)->select();
        $this->assign('lists', $list);
        return $this->fetch();
    }

    public function dayin()
    {
        $id = $this->request->param('id');
        $formData = Db::name('deposit')->where('id', $id)->find();
        $det = Db::name('deposit_log')->where('d_id',$id)->order('id desc')->find();
        $formData['user_name'] = Db::name('user')->where('id',$formData['user_id'])->value('nick');
        $product = Db::name('product')->where('id',$formData['product_id'])->find();
        $unit = '';
        if(Db::name('warehouse')->where('id',$formData['warehouse_id'])->value('type') == 1){
            $unit = Db::name('unit')->where('id',$product['decomposition_id'])->value('name');
        }else{
            $unit = Db::name('unit')->where('id',$product['unit_id'])->value('name');
        }
        $this->assign('unit',$unit);
        $formData['product_specs'] = $product['specs'];
        $formData['shop_name'] = Db::name('shop')->where('id',$formData['shop_id'])->value('name');
        $this->view->engine->layout(false);
        $this->assign('det', $det);
        $this->assign('formData', $formData);
        return $this->fetch('dayin');
        return $this->fetch();
    }
}
